package gray.android.field;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import gray.Field;
import gray.android.FactoryAndroid;
import regex.Regex;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import snippet.Snipet;

public class DateField extends LinearLayout implements Field<Date,View>, TextWatcher{
	private final EditText _field;
	private final Boolean _required;
  private final Snipet _lang;
  private final SimpleDateFormat _fmt = new SimpleDateFormat("yyyy-MM-dd");

	private DateField(Context context,final Snipet lang, String name, Character key, Boolean required) {
		super(context);
		TextView txt = new TextView(context);
		txt.setText(name);
    txt.setTextColor(0xFF000000);
		_field = new EditText(context);
		_field.addTextChangedListener(this);
		_field.setLines(1);
    _field.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                            LayoutParams.WRAP_CONTENT));
		//requestFocus();
		
		addView(txt);
		addView(_field);
		_required = required;
    _lang=lang;
	}

	public static Field<Date, View> factory(Context context,final Snipet lang, String name, Character key){
		return new DateField(context,lang, name, key, false);
	}

	public static Field<Date, View> factoryRequired(Context context,final Snipet lang, String name, Character key){
		return new DateField(context,lang, name, key, true);
	}
	
	@Override
	public View container() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public Boolean ready() {
		if (_field.getText().toString().length()==0)
			return !_required;
		return Regex.validateDate(_field.getText().toString());
	}

	@Override
    public Date input() {
        try {
            return _fmt.parse(_field.getText().toString());
        } catch (ParseException ex) {
            //Logger.getLogger(DateField.class.getName()).log(Level.SEVERE, null, ex);
            return new Date();
        }
    }
	
	@Override
	public void afterTextChanged(Editable arg0) {
		if (!Regex.validateDate(_field.getText().toString())){
			FactoryAndroid.message(this.getContext(), _lang.notDate());
			_field.setTextColor(0xFFFF0000);
		}else{
			_field.setTextColor(0xFF000000);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}
}
